<template>
  <div>
      <div class="box">
          <div class="top">
             
              <div>
                 <p  @click="getBack"><el-icon><Back /></el-icon>返回</p><p class="back"></p><p>《{{formtitle}}》试题列表</p>
             </div>
             <div>
                  <el-button @click="toAdd">添加试题</el-button>
                  <el-button type="primary" @click="toAddAll">批量添加试题</el-button>
             </div> 
          </div>
          <div class="nav">
              题目名称：<el-input v-model="form.key" @click.enter="seach" placeholder="请输入题库名称" />
              创建人:<el-input  v-model="form.admin" placeholder="请输入创建人" />
              题目类型：<el-select v-model="value" class="m-2" placeholder="请选择">
                          <el-option
                          v-for="item in options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                          />
                      </el-select>
              <el-button type="primary" @click="seach">查询</el-button>
              <el-button type="danger" disabled>批量删除</el-button>
              <el-button @click="handleExportTableData('table',formtitle)">导出excel</el-button>
              <!-- <button @click="ExportTableData('table',formtitle)">导出excel</button> -->
          </div>
          <!-- 列表 -->
          <div id="table">
              <el-table :data="tableData" style="width: 100%">
                  <el-table-column type="selection" width="55" />
                  <el-table-column label="题目名称" >
                    <template #default="scope">
                      <el-link type="primary" @click="getquestion(scope.row)" >
                        <span v-html="scope.row.title" class="span"></span>
                      </el-link>
                      
                    </template>
                  </el-table-column>
                  <el-table-column prop="type" label="题目类型" />
                  <el-table-column prop="addtime" label="创建时间" />
                  <el-table-column prop="admin" label="创建人" />
                  <el-table-column label="操作" >
                      <template #default="scope" >
                        <div class="action" style="display:flex; ">
                          <p  @click="handleEdit(scope.row)" style="color: #79bbff ; padding: 0 5px;">编辑</p>
                          <p size="small" type="danger" @click="handleDelete( scope.row.id)" style="color: #79bbff ; padding: 0 10px;">删除</p>
                        </div>
                      </template>
                  </el-table-column>
              </el-table>
          </div>
            <!-- 分页 -->
          <div class="page">
            <pages
              :total="total"
              :page="query.page"
              :pageSize="query.psize"
              @changePageSize="handleSizeChange"
              @changePage="handleCurrentChange"
            />

          </div>
          <!-- 试题详情 -->
         <div>
            <drawer v-if="isLook"></drawer>
         </div>
          <!-- 添加试题 -->
          <div>
            <questionAdd :question="question" @add="addquestion" @isOpen="isOpen"></questionAdd>
          </div>
          <!-- 批量添加 -->
          <questionAddAll  :isImport="isImport" @imports="imports"  @isImports="isImports"></questionAddAll>
      </div>
  </div>
</template>

<script setup lang="ts">
import { ref,reactive,onMounted ,toRefs,onBeforeUnmount,shallowRef,watch,provide} from "vue";
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { Back,CircleClose,CirclePlus } from '@element-plus/icons-vue'
import router from "../../router/router";
import { useRoute } from "vue-router";
import {databasequestionlist,databasequestiondel ,databasequestionadd,databasequestionaddlist } from "../../api/index";
import { ElDrawer, ElMessage} from 'element-plus'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import * as XLSX from 'xlsx'
import {saveAs} from 'file-saver'
import {handleExportTableData} from '../../utils/utils'
import pages  from "./../../components/pages/pages.vue";
import drawer from './../../components/questiondetails/questiondetails.vue'
import questionAdd from './../../components/questionadd/question.vue'
import questionAddAll from '../../components/questionadd/questionAddAll.vue'

const route =useRoute()
// 表单数据
const form =reactive({
  id:route.query.id,
  title:route.query.title,
  key:'',
  admin:'',
  
  type:'单选题',

})
// const {title}=toRefs(form)
let background=ref(true)
const total=ref(0)//分页
const radio1 = ref('1')
// 题目类型
const value = ref('')
const data: any = reactive({
isImport:false,
isLook: false,
// 试卷数据
databaseData: { id: "", title: "" },
dataLook: {},
// 试题添加
question:{
  id:0,
  testdialog:false,
  title:'试题添加',
  params:{}//当前试题
},
// 表单
test:{
  title:'',
  answer:'',//正确答案
  explains: "",//解析
  answers: [
    { answerno: "A", content: "" },
    { answerno: "B", content: "" },
    { answerno: "C", content: "" },
    { answerno: "D", content: "" },
  ],
},
query:{
  databaseid:0,
  page:1,
  psize:10,
},
dataUp:{},
blank:[]
});

const { isLook, dataLook ,blank,test,databaseData,question,dataUp,isImport,query} = toRefs(data);
provide("data", data);

const supData: any = route.query.data;
data.databaseData = JSON.parse(supData)
// console.log(data.databaseData);
const formtitle =data.databaseData.title
query.value.databaseid = JSON.parse(supData).id;
// console.log(test.value.databaseid);


watch(()=>data.test.title,() => {
if (data.params.title.match(/\[\]/g) != null) {
  data.blank = data.params.title
    .match(/\[\]/g)
    .map((item: any,index:number) => (item = data.blank[index]));
} else {
  data.blank = [];
}
},{immediate:false});
const options = [
{
      value: "单选题",
      label: "单选题",
    },
    {
      value: "多选题",
      label: "多选题",
    },
    {
      value: "问答题",
      label: "问答题",
    },
    {
      value: "判断题",
      label: "判断题",
    },
    {
      value: "填空题",
      label: "填空题",
    },
]
// 试题列表
let tableData=ref([])
// 点击添加
const toAdd=()=>{
question.value.id=0
question.value.testdialog=true
// console.log(test.value);

}
// 试题添加
const addquestion=async(row:any)=>{
// console.log(row);
let res:any=await databasequestionadd({...row,databaseid:query.value.databaseid})
// console.log(res);
if(res.errCode===10000){
  question.value.testdialog=false
  if(row.id>0){
    ElMessage.success('修改成功')
  }else{
    ElMessage.success('添加成功')
  }
  getlist(query.value)
}


}
// 编辑试题
const handleEdit = (row:any) => {
// console.log(row);
question.value.id=1
question.value.testdialog=true
question.value.params=row

}
// 清空
const isOpen = (e: any) => {
console.log(e);

if (!e[0]) {
  question.value.testdialog = e[0];
  test.value = {
  id: 0,
  databaseid: 0,
  type: "单选题",
  tags: "",
  // 内容 HTML
  title: "",
  answer: "",
  scores: null,
  explains: "",
  answers: [
    {
      answerno: "A",
      content: "",
    },
    {
      answerno: "B",
      content: "",
    },
    {
      answerno: "C",
      content: "",
    },
    {
      answerno: "D",
      content: "",
    },
  ],
};
}

};
// 试题删除 

const handleDelete =async (id:number) => {
const obj={
  id:id
}
let res:any=await databasequestiondel(obj)
// console.log(res);
if(res.errCode===10000){
  ElMessage.success('删除成功')
  getlist(query.value)
}

}

// 列表
const getlist=async (query:any)=>{
// console.log(form.id);
let res:any=await databasequestionlist(query)
console.log(res); 
if(res.errCode==10000){
  tableData.value=res.data.list
  total.value=res.data.counts
}

}
getlist(query.value)

// 分页
const handleSizeChange = (val: number) => {
// console.log(`${val} items per page`)
query.value.psize = val;  
getlist(query.value)

}
const handleCurrentChange = (val: number) => {
// console.log(`current page: ${val}`)
query.value.page = val;
getlist(query.value)

}
// 替换下划线方法
const repTitle = (title: string) => {
return title.replace(/\[\]/g, "_____,");
};
// 试题详情
const getquestion=(examInfo:any)=>{
data.isLook = true;
data.dataUp = { ...examInfo, title: repTitle(examInfo.title) };
// console.log(data.dataUp);
}

// 导出
const ExportTableData=(elId:string,downloadName?:string|null,type?:string)=>{
  let wb=XLSX.utils.table_to_book(document.getElementById(elId),{
    raw:true
  })as any
}

// 批量添加弹窗
const toAddAll=()=>{
data.isImport=true
}
// 接受批量添加传来的数据
const isImports = (e: any) => {
data.isImport = e;
};
// 批量添加掉接口
const getdatabasequestionaddlist=async (params:any)=>{
  const res:any=await databasequestionaddlist(params)
  // console.log(res);
  if(res.errCode===10000){
    data.isImports=false
    getlist(query.value)
    ElMessage.success('添加成功')
  }
    
   
  
}
// 批量添加
const imports = (e: any) => {
// console.log(e);
const AddlistParams = {
  databaseid: test.value.databaseid,
  list: e.map((item: any) => ({
    title: item.title,
    type: item.type,
    answer: item.answer,
    tags: item.tags,
    explains: item.explains,
    answers: item.answers,
  })),
};
getdatabasequestionaddlist(AddlistParams);
};
// 返回上一页
const getBack=()=>{
  router.back()
}
// 查询
const seach=()=>{

}


</script>

<style scoped lang="less">
.box{
  .top{
      display: flex;
      justify-content: space-between;
      div{
          display: flex;
          cursor:pointer;
          .back{
              display: block;
              border-right: 1px solid #ccc;
              height: 20px;
              // padding: 0 20px;
              margin: 0 20px;
              
          }
      }
  }
  .nav{
      display: flex;
      width: 1382px;
      height: 40px;
      font-size: 15px;
      text-align: center;
      line-height: 30px;
      padding: 0 5px;
      .el-input{
          width: 200px;
          height: 30px;
          margin: 0 5px;
      }

      .el-button{
      margin: 0 5px;
      }
  }
  .page{
    width: 500px;
    margin: 15px auto;
  }
  .chooses{
    .li{
      margin: 20px;
      padding: 10px;
      display: flex;
      border-radius: 5px;
      font-size: 14px;
      .round{
        width: 20px;
        height: 20px;
        border-radius: 50%;
        border: 1px #edf3f1 solid;
      }
    }
    .blueli{
      background-color: #f0faf6;
      left: 1;
    }
  }
  .judge{
    margin: 10px;
      padding: 10px;
    background-color: #f0faf6;
    span{
      margin: 10px;
      padding: 10px;
      border-radius: 5px;
      font-size: 14px;
      color: #84d5b1;
      // background-color: #f0faf6;
    }
  }
  .Short{
    margin: 10px;
      padding: 10px;
    background-color: #f6faff;
    span{
      font-size: 14px;
      color: #a0adbd;
    }
  }
  .correct{
    margin: 10px;
      padding: 10px;
    background-color: #f6faff;
    span{
      margin: 10px;
      font-size: 14px;
      color: #84d5b1;
    }
  }
  .analysis{
    margin: 10px;
      padding: 10px;
    background-color: #f6faff;
    span{
      font-size: 14px;
      color: #a0adbd;
    }
  }
  .stem{
    width: 900px;
    white-space: nowrap;
    // height: 200px;
    display: flex;
  }

  .choosebox{
    display: flex;
    width: 600px;
    margin: 10px;
    line-height: 50px;
    .textarea{
      display: flex;
      justify-content: space-between;
      line-height: 50px;
      padding: 10px;
      color: #000;
      width: 300px;
      .el-textarea{
        width: 260px;
        height: 20px;
      }
      .el-icon {
        cursor: pointer;
        color: red;
        display: block;
        line-height: 50px;
        font-size: 24px;
      }
      
    }
  }
  .Plus{
    cursor: pointer;
        font-size: 30px; 
        margin-left: 50px;
        color: rgb(89, 160, 255);
  }
  .answer{
    display: flex;
    padding: 10px;
  }
  .mb-2 {
    padding: 10px;
  }
  .scores{
    display: flex;
  }
  .btn{
    margin: 30px;
  }
}
</style>